/**
 * @describe 字符串处理
 * @author 游金宇(KM)
 * @date 2023-01-31 10:40:21
 */

type SubOptions = {
    /**截取后显示... */
    showdot?: boolean
    /**当使用showdot时是否前移一位代替... */
    removeLastChar?: boolean
}



/** 获取一个唯一标识的字符串 */
export const guid = () => {
    let guid: string = '';
    for (let i = 1; i <= 32; i++) {
        let n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if (i == 8 || i == 12 || i == 16 || i == 20) guid += '-';
    }
    return guid;
}
/**
 * 字符串截取
 * @param str     字符串
 * @param n       截取长度
 * @param showdot 是否把截取的部分用省略号代替
 */
export const sub = (str: string, n: number, showdot: boolean = true) => {

    str = decodeURIComponent(str)

    const charArray = Array.from(str);
    let length = 0;
    let result = '';

    for (let i = 0; i < charArray.length; i++) {
        const char = charArray[i];
        const charCodePoint = char.codePointAt(0);
        let charLength = 0

        if (charCodePoint) {
            if ((charCodePoint >= 0x4E00 && charCodePoint <= 0x9FFF) || (charCodePoint >= 0x3400 && charCodePoint <= 0x4DBF)) {
                charLength = 2
            } else if ((charCodePoint >= 0x0041 && charCodePoint <= 0x005A) || (charCodePoint >= 0x0061 && charCodePoint <= 0x007A)) {
                charLength = 1
            } else if (charCodePoint >= 0x0030 && charCodePoint <= 0x0039) {
                charLength = 1
            } else if (charCodePoint > 0xFFFF) {
                charLength = 2
            } else {
                charLength = Array.from(char).length
            }
        } else {
            charLength = Array.from(char).length
        }

        length += charLength;

        if (length > n) {
            if (charArray[i] && showdot) result += '...';
            break;
        }

        result += char;
    }

    return result;
};

/**
 * 计算字符串长度，中文算两个字节
 * @param str 字符串
 */
export const stringLen = (str: string) => {
    var realLength = 0,
        len = str.length,
        charCode = -1;
    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) realLength += 1;
        else realLength += 2;
    }
    return realLength;
}

/**获取url参数 */
export const getURLParameters = (url: string): { [key: string]: string } => {
    const params: { [key: string]: string } = {};
    const searchParams = new URL(url).searchParams;

    searchParams.forEach((value, key) => {
        params[key] = value;
    });

    return params;
}


// 可以将HTML字符串解析为片段
const htmlTextParser = (text: string): { type: string; content: string }[] => {
    const regex = /(<\/?[^>]+>)/g;
    const parts = text.split(regex);
    return parts.map(part => {
        if (part.match(regex)) {
            return { type: 'html', content: part };
        } else {
            return { type: 'text', content: part };
        }
    });
}

const processString = (inputString: string, htmlTag: string, size: number): string => {
    const cocosStandardSize = 2048 * 0.8 / size;

    if (inputString.length > cocosStandardSize) {
        // 分割字符串
        const regex = new RegExp(`.{1,${Math.floor(cocosStandardSize)}}`, 'g');
        const splitStrings = inputString.match(regex) || [];
        // 在每段字符串中间部分拼接HTML标签，首尾不添加标签
        const processedString = splitStrings.map((s, index) => {
            if (index === 0 || index === splitStrings.length - 1) {
                return s;
            } else {
                return `<${htmlTag}>${s}</${htmlTag}>`;
            }
        }).join('');
        return processedString;
    } else {
        return inputString;
    }
}
/**
 * 
 * @param inputString 字符串
 * @param htmlTag 标签
 * @param size 字体大小
 * @returns 
 */
export const processHtmlString = (inputString: string, size: number, htmlTag: string = 's',): string => {
    const parsedParts = htmlTextParser(inputString);
    let result = '';

    parsedParts.forEach(part => {
        if (part.type === 'text') {
            result += processString(part.content, htmlTag, size);
        } else {
            result += part.content;
        }
    });

    return result;
}